package com.msi.manning.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

/**
   	Relates to the first screen viewable for the
   	 NutritionMe Application. Search updates as
   	 the user types, results are displayed in a
   	 ListView with the option to scroll. Search
   	 queries the database to provide the results.
   	 Clicking an item in the ListView provides information
   	 on another screen (Result.java) retrieved from the database.
    @author Team SuperCool
 */

public class NutritionMe extends Activity {

	public static final int MAIN_ID = Menu.FIRST;
	protected static final int SELECTED_CHOICE = 0;
    private static final String CLASSTAG = NutritionMe.class.getSimpleName();
    private static final String URL = "http://teamsupercool.x10hosting.com/search.php";
    private static int resultSize = 0;
    private static final int ZERO = 0;
    private static final int INVALID = -1;
    
    protected ArrayList<String> result = new ArrayList<String>();
    private EditText param1Value;
    private ListView choices;
    private ProgressDialog progressDialog;

    @Override
    public void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        
        requestWindowFeature(Window.FEATURE_CONTEXT_MENU);
        
        // inflate the SAME view XML layout file as ApacheHTTPWithAuth Activity (re-use it)
        this.setContentView(R.layout.nutritionme);

        this.param1Value = (EditText) findViewById(R.id.htth_param1_value);
        this.choices = (ListView) findViewById(R.id.list_of_choices);
        
        this.param1Value.addTextChangedListener(new TextWatcher(){

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
		    	Log.d(Constants.LOGTAG, "User Inputted: " + s.toString());
		    	initListView();
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}
        });
    };
    
    
    /**
       Sets the results to the ListView
     */
    
    private void refreshFavListItems() {
        choices.setAdapter(new ArrayAdapter<String>(this,
                  android.R.layout.simple_list_item_1, this.result));
    }
    
    
    /**
       Queries the database for the List of results stored
        in List result.
       Anonymous ClickListeners are activated for each
        result in the List. This queries the result to
        provide Nutrition Facts handled by class Result.
        Class Result provides additional display functionality.
     */
    
    private void initListView() {
    	String tParam = param1Value.getText().toString();
    	if (!tParam.equals(""))
    	{
            this.result = getHttpResponse(URL + "?keyword=" + tParam);
            resultSize = result.size();
            if (resultSize == ZERO)
            {
            	resultSize = INVALID;
            	result.add("No Matches Found");
            }
            refreshFavListItems();
            choices.setOnItemClickListener(new OnItemClickListener() {
            	
            	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            			long arg3) {
	        		Intent inte = new Intent(NutritionMe.this, Result.class);
	        		inte.putExtra("choices", choices.getAdapter().getItem(arg2).toString());
	        		if (resultSize != INVALID)
	        			startActivity(inte);
	        	}
	        	
	        });
    	}
    	else
    	{
    		this.result = new ArrayList<String>();
    		refreshFavListItems();
    	}
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, MAIN_ID, 0, "Reset").setIcon(R.drawable.reset);
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
        case MAIN_ID:
            startActivity(new Intent(NutritionMe.this, NutritionMe.class));
        return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    
    
    @Override
    public void onPause() {
        super.onPause();
        if ((this.progressDialog != null) && this.progressDialog.isShowing()) {
            this.progressDialog.dismiss();
        }
    }

    
    /**
       Perform an HTTP GET with HttpUrlConnection.
       @param location Queried URL
       @return List of results
     */
    
    public ArrayList<String> getHttpResponse(String location) {
        URL url = null;
        ArrayList<String> items = new ArrayList<String>();
        
        Log.d(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " location = " + location);

        try {
            url = new URL(location);
            Log.d(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " url = " + url);
        } catch (MalformedURLException e) {
            Log.e(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " " + e.getMessage());
        }

        if (url != null) {

            try {
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                	if(!inputLine.equals("")){
                		Log.v(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " inputLine = " + inputLine);
                		items.add(inputLine);
                	}
                }

                in.close();
                urlConn.disconnect();

            } catch (IOException e) {
                Log.e(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " " + e.getMessage());
            }

        } else {
            Log.e(Constants.LOGTAG, " " + NutritionMe.CLASSTAG + " url NULL");
        }
        return items;
    }
}

